package com.huafeng.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huafeng.commonutil.CheckUtils;
import com.huafeng.mapper.SysDeptMapper;
import com.huafeng.model.base.Result;
import com.huafeng.model.constant.IdConstant;
import com.huafeng.model.entity.SysDept;
import com.huafeng.service.SysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/19 11:57
 * @Description SysDeptServiceImpl
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    private final ReentrantLock updateStatusLock = new ReentrantLock();

    @Override
    public Result findNodes() {
        List<SysDept> result = new ArrayList<>();
        // 获取根结点结合
        List<SysDept> roots = this.query().eq("parent_id", IdConstant.DEPT_ROOT_ID).list();
        // 查出所有部门
        List<SysDept> sysDeptList = this.list();

        roots.forEach(root-> {
            root.setChildren(new ArrayList<>());
            // 获取子节点
            List<SysDept> children = getChildren(root, sysDeptList);
            children.forEach(child -> {
                child.setChildren(new ArrayList<>());
                child.getChildren().addAll(getChildren(child,sysDeptList));
            });
            root.getChildren().addAll(children);
            result.add(root);
        });

        return Result.ok(result);
    }

    @Override
    public Result updateStatus(Long id, Integer status) {
        updateStatusLock.lock();
        try {
            SysDept sysDept = this.query().eq("id", id).one();
            updateStatus(status,sysDept);
            return Result.ok("修改成功");
        }finally {
            updateStatusLock.unlock();
        }
    }

    private void updateStatus(Integer status,SysDept sysDept){
        if (sysDept != null){
            // 更新自身
            this.update().set("status",status).eq("id",sysDept.getId()).update();
            // 查询是否有子部门
            List<SysDept> sysDeptList = this.query().eq("parent_id", sysDept.getId()).list();
            if (!CollectionUtils.isEmpty(sysDeptList)){
                // 如果有子部门，子部门全都修改成一样的状态
                List<Long> ids = sysDeptList.stream().map(SysDept::getId).collect(Collectors.toList());
                this.update().set("status",status).in("id",ids).update();
                sysDeptList.forEach(dept -> updateStatus(status,dept));
            }
        }
    }

    private List<SysDept> getChildren(SysDept sysDept,List<SysDept> sysDeptList){
        Long deptId = sysDept.getId();
        return sysDeptList.stream().filter(sysDept1 -> Objects.equals(sysDept1.getParentId(), deptId)).collect(Collectors.toList());
    }
}
